package com.yxsk.relay.job.admin.core.executor.quartz.listener;

import com.yxsk.relay.job.admin.core.executor.quartz.context.QuartzRemoteJobExecuteContext;
import com.yxsk.relay.job.admin.data.entity.JobExecuteLog;
import com.yxsk.relay.job.admin.data.service.JobExecuteLogService;
import com.yxsk.relay.job.component.common.exception.RelayJobRuntimeException;
import com.yxsk.relay.job.component.common.protocol.message.execute.JobExecuteResponse;
import com.yxsk.relay.job.component.common.vo.ExecuteResult;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author 11376
 * @CreaTime 2019/6/22 23:55
 * @Description quartz远程任务执行监听
 */
@Slf4j
public class QuartzAsyncRemoteJobExecuteListener extends QuartzRemoteJobExecuteListener {

    public QuartzAsyncRemoteJobExecuteListener(JobExecuteLogService executeLogService) {
        super(executeLogService);
    }

    /**
     * @Author 1137
     * @Description 异步任务此处会回调两次, 只会
     * @Date
     * @Param
     * @return
     */
    @Override
    public void onFinish(QuartzRemoteJobExecuteContext context) {
        JobExecuteLog executeLog = this.executeLogService.findById(context.getRequest().getSerialNo());
        if (ExecuteResult.ExecuteResultCode.EXECUTING.getCode().equals(executeLog.getExecuteStatus())) {
            if (log.isDebugEnabled()) {
                log.debug("Job execute log already processed, log id: {}", context.getRequest().getSerialNo());
            }
            return;
        }
        if (executeLog == null) {
            throw new RelayJobRuntimeException("未找到任务执行日志");
        }
        JobExecuteResponse executeResponse = context.getResponse().getData();
        executeLog.setEndTime(executeResponse.getRespTime());
        executeLog.setExecuteStatus(executeResponse.getExecuteStatus());
        executeLog.setExecuteResult(executeResponse.getResult());
        executeLog.setExecuteErrorMessage(executeResponse.getErrorMsg());
        this.executeLogService.updateByIdAndExecuteStatus(executeLog, ExecuteResult.ExecuteResultCode.EXECUTING.getCode());
    }

}
